<template>
    <div class="main_container">
        <div class="Header">
            <!-- 第一层区域 -->
            <el-row>
                <el-col :span="10">
                    <div>
                        <el-input placeholder="请输入学号或者姓名" v-model="param.username" clearable>
                            <el-select v-model="param.id" slot="prepend" placeholder="请选择">
                                <el-option v-for="(item,index) in classes" :key="index" :label="item.className"
                                    :value="item.id"></el-option>
                            </el-select>
                            <el-button @click="getStudentList" class="Search" slot="append"
                                icon="el-icon-search"></el-button>
                        </el-input>
                    </div>
                </el-col>

                <el-col :span="14">
                    <div>
                        <el-button type="primary" @click="AddClassFold=true">添加班级</el-button>
                        <el-button type="primary" @click="ClassManagementFold=true">班级管理</el-button>
                        <el-button type="primary" @click="AddStudentFold=true">添加学生</el-button>
                    </div>
                </el-col>
            </el-row>

            <!-- 添加班级对话框 -->
            <el-dialog title="添加班级" :visible.sync="AddClassFold" width="30%">
                <!-- TODO 这里需要将这个地址换成实际的地址 -->
                <div><strong>确保文件中有姓名，学号两列</strong></div>
                <el-upload class="upload-demo" drag action="http://127.0.0.1:8000/teacher/upload" multiple
                    :headers="headers" :on-success="handleSuccess">
                    <i class="el-icon-upload"></i>
                    <div style="text-align: center;"><strong>请使用班级名称作为文件名</strong></div>

                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传excel文件,且不超过2M</div>
                </el-upload>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="AddClassFold = false">取 消</el-button>
                    <el-button type="primary" @click="AddClassFold = false">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 班级管理对话框 -->
            <el-dialog title="班级管理" :visible.sync="ClassManagementFold" width="40%">
                <el-table :data="classes" style="width: 100%">
                    <el-table-column prop="className" label="班级" width="180">
                    </el-table-column>
                    <el-table-column label="是否默认" width="180">
                        <template slot-scope="scope">
                            <span> {{ scope.row.defaultClass===1?"是":"否"}} &nbsp;</span>
                            <el-button type="success" size="mini"
                                @click="changeDefaultClass(scope.row.id,scope.row.defaultClass)">设为默认</el-button>
                        </template>
                    </el-table-column>

                    <el-table-column label=" 操作" width="180">
                        <template slot-scope="scope">
                            <el-button type="danger"
                                @click="deleteClass(scope.row.id,scope.row.defaultClass)">删除班级</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="ClassManagementFold = false">关 闭</el-button>
                </span>
            </el-dialog>

            <!-- 添加学生的对话框 -->
            <el-dialog class="addStudentDialog" title="添加学生" :visible.sync="AddStudentFold" width="30%"
                :before-close="handleaddStudentClose">
                <el-form :model="AddStudentparams">
                    <el-form-item label="姓名：">
                        <el-input v-model="AddStudentparams.username"></el-input>
                    </el-form-item>
                    <el-form-item label="学号：">
                        <el-input v-model="AddStudentparams.studentNumber"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="AddStudentparams.classId" placeholder="请选择班级">
                            <el-option v-for="(item,index) in classes" :key="index" :label="item.className"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="AddStudentFold = false">取 消</el-button>
                    <el-button type="primary" @click="AddStudent">确 定</el-button>
                </div>
            </el-dialog>


        </div>

        <!-- 第二层区域,主要区域 -->
        <el-table :data="students" style="width: 100%" stripe>
            <el-table-column type="index" label="序号" width="150"></el-table-column>
            <el-table-column prop="username" label="姓名" width="200"></el-table-column>
            <el-table-column prop="studentNumber" label="学号" width="200"></el-table-column>
            <el-table-column label="班级" width="280">
                <template slot-scope="scope">
                    <div>{{ getUserName(scope.row.classId) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280">
                <template slot-scope="scope">
                    <!-- 重置密码 -->
                    <el-tooltip content="重置密码" placement="top" :enterable="false">
                        <el-button type="warning" size="mini" @click="resetPassword(scope.row.id)">重置</el-button>
                    </el-tooltip>
                    <!-- 删除同学 -->
                    <el-button type="danger" size="mini"
                        @click="deleteStudent(scope.row.id,scope.row.username)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 删除学生确定框 -->
        <el-dialog title="提示框" :visible.sync="deleteStudentFold" width="30%" :before-close="handledeleteStudentClose">
            <span>确定删除{{ deleteStudentUsername }}这个学生</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteStudentFold = false">取 消</el-button>
                <el-button type="primary" @click="deleteStudentById">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 第三层区域,分页部分 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="param.currentPage" :page-sizes="[5, 10, 20]" :page-size="param.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

    </div>
</template>

<script>
    export default {
        watch: {
            'param.id': { // 监视param对象中的id属性变化  
                handler(newVal) {
                    // TODO 注意，这里的这个username清空之后还要再发一次请求。后面再处理
                    this.param.username = ""
                    // 因为  param.id 发生变化 这里就会自动发送一次请求
                    this.getStudentList()
                },
            },
            'param.username': { // 监视param对象中的username属性是否为空 
                handler(newVal) {
                    if (newVal === null || newVal === "") {
                        this.getStudentList()
                    }
                },
            },
        },

        created() {
            this.getCalssList()
        },

        data() {
            return {
                // 班级信息
                classes: [],
                // 分页查询参数
                param: {
                    id: null,       // 班级id
                    username: "",   // 学号或者姓名
                    currentPage: 1,  // 页数
                    pageSize: 5      // 每页记录数
                },
                // 学生信息总条数
                total: null,
                // 学生信息
                students: [],
                // 添加学生参数对象
                AddStudentparams: {
                    classId: null,           // 班级
                    username: "",            // 姓名
                    studentNumber: ""        // 学号
                },


                // 对话框控制变量
                AddClassFold: false,            // 添加班级
                ClassManagementFold: false,     // 班级管理
                AddStudentFold: false,          // 添加学生
                deleteStudentFold: false,       // 删除学生提示框

                deleteStudentid: null,          // 删除学生id储存
                deleteStudentUsername: "",       // 删除学生姓名储存
                // 上传文件需要的token
                headers: {
                    Authorization: window.sessionStorage.getItem('token')
                }
            };
        },
        methods: {
            // 上传班级文件的返回信息 -已检查
            handleSuccess(response, file, fileList) {
                if (response.code == 200) {
                    this.AddClassFold = false
                    this.getCalssList()
                    return this.$message.success("添加班级成功");
                }
                if (response.code == 301) {
                    return this.$message.error("该文件并没有解析到学生数据");
                }
                if (response.code == 305) {
                    return this.$message.error(response.msg);
                }
                if (response.code == 502) {
                    return this.$message.error("文件解析失败");
                }
                if (response.code == 500) {
                    return this.$message.error("网络错误，或者学号,班级名有冲突，请联系管理员");
                }
            },
            // 获取班级信息
            async getCalssList() {
                const { data: res } = await this.$axios.get("/getClasses")
                this.classes = res.data
                this.param.id = res.id
            },
            // 分页查询
            async getStudentList() {
                const { data: res } = await this.$axios.post("/getStudent", this.param)
                if (res.code === 200) {
                    this.total = res.data.total
                    this.students = res.data.records
                    return 
                }
                return this.$message.error("网络错误")
            },
            // 更改默认班级
            async updateDefaultClass(id, defaultClass) {
                const { data: res } = await this.$axios.get('/updateDefaultClass', {
                    params: {
                        id: id,
                        defaultClass: defaultClass
                    }
                })
                if (res.code != 200) { return this.$message.console.error(); ('修改失败') }
                this.getCalssList() // 这里班级信息发生变化，重新发送一次请求
                this.$message.success('修改成功')
            },
            // 删除班级
            async deleteClassById(id) {
                const { data: res } = await this.$axios.delete("/deleteClass", {
                    params: {
                        id: id
                    }
                })
                if (res.code != 200) { return this.$message.console.error(); ('删除失败') }
                this.getCalssList() // 这里班级信息发生变化，重新发送一次请求
                this.$message.success('删除成功')
            },
            // 添加学生
            async AddStudent() {
                if (this.AddStudentparams.classId === null ||
                    this.AddStudentparams.username === null ||
                    this.AddStudentparams.username === "" ||
                    this.AddStudentparams.studentNumber === "" ||
                    this.AddStudentparams.studentNumber === null
                ) {
                    return this.$message("请将信息填完整")
                }
                const { data: res } = await this.$axios.post("/addStudent", this.AddStudentparams)
                if (res.code === 200) {
                    this.getStudentList()
                    this.AddStudentFold = false
                    return this.$message.success("添加成功")
                }
                if (res.code === 510) {
                    return this.$message.error("学生已经存在了---学号重复")
                }
                return this.$message.error("添加失败")
            },
            // 根据id重置密码
            async resetPasswordById(id) {
                const { data: res } = await this.$axios.get("/resetPassword", {
                    params: {
                        id: id
                    }
                })
                if (res.code === 200) {
                    return this.$message.success("重置密码成功")
                }
                this.$message.error("网络异常")
            },
            // 删除学生
            async deleteStudentById() {
                if (this.deleteStudentid === null) {
                    return this.$message.error("系统故障！请联系管理员")
                }
                const { data: res } = await this.$axios.delete("/deleteStudent", {
                    params: {
                        id: this.deleteStudentid
                    }
                })
                if (res.code === 200) {
                    this.getStudentList()
                    this.deleteStudentFold = false
                    return this.$message.success("删除成功")
                }
                return this.$message.error("删除失败")
            },

            // 根据id查询对应的班级
            getUserName(id) {
                const classes = this.classes.find(classes => classes.id === id);
                return classes ? classes.className : ''; // 返回用户名或者空字符串作为占位符  
            },
            handleSizeChange(newPageSize) {
                this.param.pageSize = newPageSize
                this.getStudentList()
            },
            handleCurrentChange(newCurrentPage) {
                this.param.currentPage = newCurrentPage
                this.getStudentList()
            },
            // 更改默认班级
            changeDefaultClass(id, defaultClass) {
                if (defaultClass === 1) {
                    return this.$message("此班级已经是默认班级了")
                }
                this.updateDefaultClass(id, defaultClass)
            },
            // 删除班级
            deleteClass(id, defaultClass) {
                if (defaultClass === 1) {
                    return this.$message("对不起，此班级是默认班级，不能删除")
                }
                this.deleteClassById(id)
            },
            // 添加学生对话框关闭前的回调
            handleaddStudentClose(done) {
                this.AddStudentparams.classId = null,             // 班级
                    this.AddStudentparams.username = "",              // 姓名
                    this.AddStudentparams.studentNumber = "",          // 学号
                    done()
            },
            // 删除学生对话框关闭前的回调
            handledeleteStudentClose(done) {
                this.deleteStudentUsername = "",
                    this.deleteStudentid = null,
                    done()
            },
            // 学生重置密码
            resetPassword(id) {
                this.resetPasswordById(id)
            },
            // 删除学生对话框
            deleteStudent(id, username) {
                this.deleteStudentUsername = username
                this.deleteStudentid = id
                this.deleteStudentFold = true
            },

        }
    }
</script>

<style lang="less" scoped>
    /* 全局样式 */
    .main_container {
        height: 100%;
    }

    /* 头部样式 */
    .Header {
        margin-bottom: 15px;

        /* 选择框 */
        .el-select {
            width: 100px;
        }

        /* 三个按钮 */
        .el-col div {
            text-align: right;

            .el-button {
                margin-right: 22px;
            }
        }
    }

    /* 添加学生对话框样式 */
    .addStudentDialog {
        .el-select {
            width: 200px;
        }

        .el-input {
            width: 300px;
        }
    }
</style>